/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EditarModelo.java
 *
 * Created on 05/04/2011, 01:24:05
 */
package editar;

import Classe.BD;
import Classe.Marca;
import Classe.Modelo;
import Classe.Validacao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author gladson
 */
public class EditarModelo extends Validacao {

    /** Creates new form EditarModelo */
    public EditarModelo() {
        initComponents();
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        iniciar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jpnCadastroModelo = new javax.swing.JPanel();
        btSalvarModelo = new javax.swing.JButton();
        btSairModelo = new javax.swing.JButton();
        sTxtModeloModelo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cbmodelo = new javax.swing.JComboBox();
        lblModeloModelo = new javax.swing.JLabel();
        cbmarca = new javax.swing.JComboBox();
        lblMarcaModelo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jpnCadastroModelo.setBackground(new java.awt.Color(255, 255, 255));
        jpnCadastroModelo.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Editar Cadastro Modelo", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("PMingLiU", 0, 36))); // NOI18N

        btSalvarModelo.setFont(new java.awt.Font("Arial", 0, 12));
        btSalvarModelo.setText("Salvar");
        btSalvarModelo.setToolTipText("Salvar");
        btSalvarModelo.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
        btSalvarModelo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarModeloActionPerformed(evt);
            }
        });

        btSairModelo.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btSairModelo.setText("Sair");
        btSairModelo.setToolTipText("Sair");
        btSairModelo.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
        btSairModelo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairModeloActionPerformed(evt);
            }
        });

        sTxtModeloModelo.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel1.setText("Alterar para:");

        cbmodelo.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
        cbmodelo.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        cbmodelo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbmodeloItemStateChanged(evt);
            }
        });

        lblModeloModelo.setFont(new java.awt.Font("Arial", 1, 11));
        lblModeloModelo.setText("Modelo");

        cbmarca.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));
        cbmarca.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        cbmarca.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbmarcaItemStateChanged(evt);
            }
        });

        lblMarcaModelo.setFont(new java.awt.Font("Arial", 1, 11));
        lblMarcaModelo.setText("Marca");

        javax.swing.GroupLayout jpnCadastroModeloLayout = new javax.swing.GroupLayout(jpnCadastroModelo);
        jpnCadastroModelo.setLayout(jpnCadastroModeloLayout);
        jpnCadastroModeloLayout.setHorizontalGroup(
            jpnCadastroModeloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnCadastroModeloLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnCadastroModeloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblMarcaModelo)
                    .addComponent(lblModeloModelo)
                    .addComponent(cbmarca, javax.swing.GroupLayout.Alignment.TRAILING, 0, 448, Short.MAX_VALUE)
                    .addComponent(cbmodelo, 0, 448, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(sTxtModeloModelo, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
                    .addGroup(jpnCadastroModeloLayout.createSequentialGroup()
                        .addComponent(btSalvarModelo)
                        .addGap(18, 18, 18)
                        .addComponent(btSairModelo)))
                .addContainerGap())
        );

        jpnCadastroModeloLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btSairModelo, btSalvarModelo});

        jpnCadastroModeloLayout.setVerticalGroup(
            jpnCadastroModeloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnCadastroModeloLayout.createSequentialGroup()
                .addComponent(lblMarcaModelo)
                .addGap(1, 1, 1)
                .addComponent(cbmarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblModeloModelo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbmodelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sTxtModeloModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jpnCadastroModeloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btSairModelo)
                    .addComponent(btSalvarModelo))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        jpnCadastroModeloLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btSairModelo, btSalvarModelo});

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpnCadastroModelo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpnCadastroModelo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-508)/2, (screenSize.height-294)/2, 508, 294);
    }// </editor-fold>//GEN-END:initComponents

    private void btSairModeloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairModeloActionPerformed
        this.dispose();
        // TODO add your handling code here:
}//GEN-LAST:event_btSairModeloActionPerformed

    private void btSalvarModeloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarModeloActionPerformed
        if (validar()) {//confirmando se a validação dos campos pelo metodo validação

            try {
                Modelo modelo = new Modelo();
                Modelo m = (Modelo) cbmodelo.getSelectedItem();

                modelo.setModelo(sTxtModeloModelo.getText().trim().toUpperCase());
                Marca itemMarca = (Marca) cbmarca.getSelectedItem();
                String sql = "UPDATE MODELO SET MODELO=?,ID_MARCA=? WHERE ID_MODELO=?";

                Object[] parametros = {modelo.getModelo(), itemMarca.getIdMarca(), m.getIdModelo()};
                Object[] tipos = {String.class, Integer.class, Integer.class};


                BD banco = new BD();
                banco.executar(sql, parametros, tipos);
                JOptionPane.showMessageDialog(rootPane, "Atualização realizada com sucesso");
                sTxtModeloModelo.setText("");
                this.iniciar();
            } catch (Exception ex) {
                ex.printStackTrace();

            }
        }
    }//GEN-LAST:event_btSalvarModeloActionPerformed

    private void cbmarcaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbmarcaItemStateChanged


        cbmodelo.removeAllItems(); // limpa a caixa atual.

        if (cbmarca.getSelectedItem() != null) {

            Marca itemMarca = (Marca) cbmarca.getSelectedItem();

            String sql = "Select * from modelo where id_marca =" + itemMarca.getIdMarca() + " order by modelo";

            BD bd = new BD();
            ResultSet r;
            try {
                r = bd.consultar(sql);



                cbmodelo.addItem(null);
                while (r.next()) {
                    Modelo modeloVei = new Modelo();

                    modeloVei.setIdModelo(r.getInt("id_modelo"));
                    modeloVei.setModelo(r.getString("modelo"));
                    cbmodelo.addItem(modeloVei);
                }

            } catch (ClassNotFoundException ex) {
                Logger.getLogger(EditarModelo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(EditarModelo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_cbmarcaItemStateChanged

    private void cbmodeloItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbmodeloItemStateChanged
        if (cbmodelo.getSelectedItem() != null) {
            sTxtModeloModelo.setEnabled(true);
            Modelo m = (Modelo) cbmodelo.getSelectedItem();
            sTxtModeloModelo.setText(m.getModelo());
        } else {
            sTxtModeloModelo.setText("");
        }
    }//GEN-LAST:event_cbmodeloItemStateChanged
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new EditarModelo().setVisible(true);


            }
        });


    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btSairModelo;
    private javax.swing.JButton btSalvarModelo;
    private javax.swing.JComboBox cbmarca;
    private javax.swing.JComboBox cbmodelo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jpnCadastroModelo;
    private javax.swing.JLabel lblMarcaModelo;
    private javax.swing.JLabel lblModeloModelo;
    private javax.swing.JTextField sTxtModeloModelo;
    // End of variables declaration//GEN-END:variables

    private void iniciar() {
        sTxtModeloModelo.setEnabled(false);
        String sql = "Select * from marca order by marca";
        BD bd = new BD();
        ResultSet r1;
        try {
            r1 = bd.consultar(sql);


            cbmarca.removeAllItems();
            cbmarca.addItem(null);

            while (r1.next()) {
                Marca marca = new Marca();
                marca.setIdMarca(r1.getInt("id_marca"));
                marca.setNomeMarca(r1.getString("marca"));
                cbmarca.addItem(marca);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(EditarModelo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(EditarModelo.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public boolean validar() {
        boolean Resultado = true;

        if (cbmarca.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(rootPane, "Seleção do campo Marca Obrigatória!!");
        } else if (cbmodelo.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(rootPane, "Seleção do campo Modelo Obrigatória!!");
            Resultado = false;
        } else if (validarModelo(sTxtModeloModelo.getText().trim()) == false) {
            Resultado = false;
        }

        return Resultado;
    }
}
